/**
 * 成品明细库存表
 */
var parameter = getRequest();
var username = parameter['username'];//参数名

//库存表
$(function () {

    // $("#start").textbox({disabled: true});
    // $("#end").textbox({disabled: true});

    //客户下拉
    getdropdownDataB();

    initKendoUiGrid();
    btn_refresh();
});

/**
 * 将数组去重
 * @param arr
 * @param attribute
 * @returns {[]}
 */
function unique(arr, attribute) {
    let new_arr = [];
    let json_arr = [];
    for (let i = 0; i < arr.length; i++) {
        if (new_arr.indexOf(arr[i][attribute]) == -1) {
            new_arr.push(arr[i][attribute]);
            json_arr.push(arr[i]);
        }
    }
    return json_arr;
}

// 构建表结构
function initKendoUiGrid(data) {

    var iid = new kendo.data.DataSource({data: []});
    var bill_code = new kendo.data.DataSource({data: []});
    var bill_date = new kendo.data.DataSource({data: []});
    var client_name = new kendo.data.DataSource({data: []});
    var order_code = new kendo.data.DataSource({data: []});
    var goods_sid = new kendo.data.DataSource({data: []});
    var color = new kendo.data.DataSource({data: []});
    var color_code = new kendo.data.DataSource({data: []});
    var price = new kendo.data.DataSource({data: []});
    var amount = new kendo.data.DataSource({data: []});
    var kilo = new kendo.data.DataSource({data: []});
    var account_kilo= new kendo.data.DataSource({data: []});
    var money = new kendo.data.DataSource({data: []});
    var remark = new kendo.data.DataSource({data: []});
    var driver = new kendo.data.DataSource({data: []});
    var license_number = new kendo.data.DataSource({data: []});
    var stevedore = new kendo.data.DataSource({data: []});
    var remarkdetail = new kendo.data.DataSource({data: []});
    var assemble_id = new kendo.data.DataSource({data: []});

    var dataSource = new kendo.data.DataSource({
        data: data,
        schema: {
            model: {
                fields: {
                    // amount: {type: "number"},
                    kilo: {type: "number"},
                    account_kilo: {type: "account_kilo"},
                    money: {type: "money"},

                }
            }
        },
        aggregate: [
            // {field: "amount", aggregate: "sum"},
            {field: "kilo", aggregate: "sum"},
            {field: "account_kilo", aggregate: "sum"},
            {field: "money", aggregate: "sum"},
        ],

        change: function (e) {
            //获取过滤条件
            let filtrer = this.filter();
            //获取所有数据
            let allData = this.data();
            //进行过滤条件的筛选
            let query = new kendo.data.Query(allData);
            //获取过过滤后的数据
            let data = query.filter(filtrer).data;
            iid.data(unique(data, 'iid'));
            bill_code.data(unique(data, 'bill_code'));
            client_name.data(unique(data, 'client_name'));
            order_code.data(unique(data, 'order_code'));
            goods_sid.data(unique(data, 'goods_sid'));
            color.data(unique(data, 'color'));
            color_code.data(unique(data, 'color_code'));
            remark.data(unique(data, 'remark'));
            driver.data(unique(data, 'driver'));
            license_number.data(unique(data, 'license_number'));
            stevedore.data(unique(data, 'stevedore'));
            remarkdetail.data(unique(data, 'remarkdetail'));
            bill_code.data(unique(data, 'bill_code'));

        },
        pageSize: 200,
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text == '查询' || (btn.linkbutton('options').text == '过滤')) {
                    btn.linkbutton('disable')
                }
            })
        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text == '查询' || (btn.linkbutton('options').text == '过滤')) {
                    btn.linkbutton('enable')
                }
            })
        }
    });
    var grid = $("#bill").kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: true,
        title: "报表",
        columnMenu: {
            sortable: true
        },
        excel: {
            fileName: "发货对账明细.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        pageable: {
            pageSize: 200
        },
        dataSource: dataSource,
        columns: [
            {
                field: "", title: "序号", width: 30,
                template: "<span class='row_number'></span>", width: 40
            },
            {
                field: 'iid',
                title: '成品发货主表主键',
                footerTemplate: '总计:',
                width: 80,
                hidden: true,
                filterable: {multi: true, search: true, dataSource: iid},
                footerAttributes: {style: "text-align:right;"},
                attributes: {style: "text-align:center;white-space:nowrap;text-overflow:ellipsis;"},
                headerAttributes: {style: 'text-align:center;'}
            },
            {
                field: "bill_date",
                title: '发货日期',
                footerTemplate: '总计:',
                width: 120,
                filterable: {multi: true, search: true, dataSource: bill_date},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'bill_code',
                title: '发货单号',
                width: 130,
                filterable: {multi: true, search: true, dataSource: bill_code},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'assemble_id',
                title: '缸号',
                width: 80,
                filterable: {multi: true, search: true, dataSource: assemble_id},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'client_name',
                title: '客户名称',
                width: 120,
                filterable: {multi: true, search: true, dataSource: client_name},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'order_code',
                title: '订单号',
                width: 120,
                filterable: {multi: true, search: true, dataSource: order_code},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'goods_sid',
                title: '品名',
                width: 200,
                filterable: {multi: true, search: true, dataSource: goods_sid},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },

            {
                field: 'color',
                title: '颜色',
                width: 120,
                filterable: {multi: true, search: true, dataSource: color},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'kilo',
                title: '发货重量',
                width: 120,
                template: item => item['kilo'] ? parseFloat(item['kilo']).toFixed(1) : '',
                format: "{0:n1}",
                footerTemplate: '#=kendo.format("{0:n1}",sum)#',
                footerAttributes: {style: "text-align:right;"},
                attributes: {style: "text-align:right;",'class': 'kendo-custum-number'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'account_kilo',
                title: '调整/对账重',
                width: 140,
                template: item => item['account_kilo'] ? parseFloat(item['account_kilo']).toFixed(1) : '',
                format: "{0:n1}",
                footerTemplate: '#=kendo.format("{0:n1}",sum)#',
                footerAttributes: {style: "text-align:right;"},
                attributes: {style: "text-align:right;",'class': 'kendo-custum-number'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'price',
                title: '单价',
                width: 100,
                template: item => item['price'] ? parseFloat(item['price']).toFixed(2) : '',
                filterable: {multi: true, search: true, dataSource: price},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'money',
                title: '金额',
                width: 120,
                template: item => item['money'] ? parseFloat(item['money']).toFixed(2) : '',
                format: "{0:n1}",
                footerTemplate: '#=kendo.format("{0:n1}",sum)#',
                footerAttributes: {style: "text-align:right;"},
                attributes: {style: "text-align:right;",'class': 'kendo-custum-number'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },

            {
                field: "remarkdetail",
                title: '明细备注',
                width: 150,
                filterable: {multi: true, search: true, dataSource: remarkdetail},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: "remark",
                title: '发货单备注',
                width: 100,
                filterable: {multi: true, search: true, dataSource: remark},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            // {
            //     field: "driver",
            //     title: '驾驶员',
            //     width: 100,
            //     filterable: {multi: true, search: true, dataSource: driver},
            //     attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
            //     headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            // },
            // {
            //     field: "license_number",
            //     title: '车牌号',
            //     width: 100,
            //     filterable: {multi: true, search: true, dataSource: license_number},
            //     attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
            //     headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            // },
            // {
            //     field: "stevedore",
            //     title: '装卸工',
            //     width: 100,
            //     filterable: {multi: true, search: true, dataSource: stevedore},
            //     attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
            //     headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            // },
            {
                field: "",
                title: '.',
                width: 20,
                filterable: {multi: true, search: true, dataSource: ''},
                attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
        ],
        reorderable: true,
        height: '99%',
        dataBound: function () {
            var rows = this.items();
            $(rows).each(function () {
                var index = $(this).index() + 1;
                var rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
            });
            // 行样式
            // let kgrid = $("#bill").data("kendoGrid");
            // let trs = kgrid.tbody.find("tr");
            // trs.each(function (i, row) {
            //     let data = kgrid.dataItem(row);
            //     let finished = data.finished;
            //     if (finished === 1) $(row).css("color", "#0f0cd0");
            // });
        },
    });
    var grid01 = $("#bill").data("kendoGrid");
    //双击事件
    grid.on('dblclick', 'tr', function () {
        //  代码
        // var kGrid = $("#bill").data("kendoGrid");
        // var row = kGrid.select();
        // var dataItem = kGrid.dataItem(row);
        // var id = dataItem['iid'];
        // var bill_code = dataItem['bill_code'];
        // window.parent.addTab('成品发货-' + bill_code,'main/html/CPGL/cpfhbillprint.html?mainId='+ id+'&userName='+username);
    });
    //右击事件
    grid.on('contextmenu', 'tr', function (e) {
        e.preventDefault();
        //  代码

    });
    //  单击事件
    grid.on('click', 'tr', function () {
        //  代码

    });
}

//刷新
function btn_refresh() {
    var kGrid = $("#bill").data("kendoGrid");
    var data1 = $('#start').datebox('getValue');
    var data2 = $('#end').datebox('getValue');
    var m_khid = $("#client").combobox('getValue');
    $.ajax({
        url: strLin + 'dynamicQuery/callProc',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(['usp_getclientduizhang',data1,data2,m_khid]),
        contentType: "application/json;charset=UTF-8",
        success: function (cdata) {
            let data=cdata.data;
            console.log(data);
            kGrid.dataSource.data(data);
        }

    });
}

//打印
function btn_print() {
    let kGrid = $("#bill").data("kendoGrid");
    if (kGrid == undefined) {
        $.messager.alert('提示', '网格组件异常！请刷新重试！');
        return;
    }
    let filtrer = kGrid.dataSource.filter();
    let allData = kGrid.dataSource.data();
    let query = new kendo.data.Query(allData);
    let data = query.filter(filtrer).data;
    if (data != undefined && data.length > 0) {
        let arr = [];
        for (let i = 0; i < data.length; i++) {
            let item = data[i]['planId'];
            if (item) arr.push(item);
        }
        if (arr.length <= 0) return;
        let reportlets = [];
        let printTemplate = {};
        printTemplate.ids = arr.join(',');
        printTemplate.reportlet = PRINT_TEMPLATE_NAME;
        reportlets.push(printTemplate);
        if (reportlets.length <= 0) {
            $.messager.show({title: '提示', msg: '没有明细！无法打印！'});
            return;
        }
        let config = {
            url: "ReportServer",
            isPopUp: false,
            data: {
                reportlets: reportlets
            }
        };
        FR.doURLPDFPrint(config);
    }
}

//导出
function btn_export() {
    let kGrid = $("#bill").data("kendoGrid");
    if (kGrid == undefined) {
        $.messager.alert('提示', '网格组件异常！请刷新重试！');
        return;
    }
    kGrid.saveAsExcel();
}

//重置
function btn_reset() {
    $.messager.show('提示', '该页面暂无chongzh业务！');
}

//  清除
function btn_cancel_filter() {
    let kGrid = $("#bill").data("kendoGrid");
    if (kGrid != undefined) {
        kGrid.dataSource.filter({});
    }
}

//右键菜单弹出框
function menuHandler() {

}

//关闭当前标签页事件
function closeTab() {
    window.parent.closeTab();
}

//颜色格式化
function styler(v, r, i) {
    return v ? "background-color:" + v + ";color:" + v + ";" : "";
}


//设置所有下拉数据
function getdropdownDataB() {
    //设置客户下拉
    $.ajax({
        url: strLin + 'contact/selectAll',
        type: 'get',
        dataType: 'json',
        success: function (cdata) {
            $('#client').combobox({
                valueField: 'sid',
                textField: 'sname',
                data:cdata.data
            });
        }
    });
}


//打印
function print_duizhang() {
    console.log('打印');
    var data1 = $('#start').datebox('getValue');
    var data2 = $('#end').datebox('getValue');
    var m_khid = $("#client").combobox('getValue');

    var strurl = strLinprint + "ReportServer?reportlet=clientfhduizhang.cpt&SDate=" + data1+"&EDate=" + data2+"&client_sid=" + m_khid;
    window.open(strurl);

}